/**
=========================================================
* Material Dashboard 2 React - v2.2.0
=========================================================

* Product Page: https://www.creative-tim.com/product/material-dashboard-react
* Copyright 2023 Creative Tim (https://www.creative-tim.com)

Coded by www.creative-tim.com

 =========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/

// @mui material components
import Grid from "@mui/material/Grid";
import Card from "@mui/material/Card";

// Material Dashboard 2 React components
import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography";

// Material Dashboard 2 React example components
import DashboardLayout from "examples/LayoutContainers/DashboardLayout";
import DashboardNavbar from "examples/Navbars/DashboardNavbar";
import Footer from "examples/Footer";
import DownloadList from "examples/Downloading/DownloadList";
import { useEffect, useState } from "react";
import http from "../../utils/http/http";
import generateId from "../../utils/http/generateId";
import byteConversion from "../../utils/http/byteConversion";
import formatSeconds from "../../utils/conversion/time";
import MDProgress from "../../components/MDProgress";

import PropTypes from "prop-types";
import substrLength from "../../utils/string/substrLength";

function Downloading() {
  const [data, setData] = useState([]);

  useEffect(() => {
    // 发起POST请求;
    http
      .post("http://115.171.37.56:6800/jsonrpc", {
        jsonrpc: "2.0",
        method: "aria2.tellActive",
        id: generateId(),
        params: [
          [
            "gid",
            "totalLength",
            "completedLength",
            "uploadSpeed",
            "downloadSpeed",
            "connections",
            "numSeeders",
            "seeder",
            "status",
            "errorCode",
            "verifiedLength",
            "verifyIntegrityPending",
            "files",
            "bittorrent",
            "infoHash",
          ],
        ],
      })
      .then((response) => {
        // 处理响应数据
        let apiResult = response.result;
        setData(apiResult);
        //console.log(apiResult);
      })
      .catch((error) => {
        // 处理错误
        // 处理
        console.error(error);
      });
  }, []);

  const Project = ({ name }) => (
    <MDBox display="flex" alignItems="center" lineHeight={1}>
      <MDTypography display="block" variant="button" fontWeight="medium" ml={1} lineHeight={1}>
        {name}
      </MDTypography>
    </MDBox>
  );
  Project.propTypes = {
    name: PropTypes.string, //加上这句就好了
  };

  const Progress = ({ color, value }) => (
    <MDBox display="flex" alignItems="center">
      <MDTypography variant="caption" color="text" fontWeight="medium">
        {value}%
      </MDTypography>
      <MDBox ml={0.5} width="9rem">
        <MDProgress variant="gradient" color={color} value={value} />
      </MDBox>
    </MDBox>
  );
  Progress.propTypes = {
    color: PropTypes.string,
    value: PropTypes.string, //加上这句就好了
  };

  //const { columns: pColumns, rows: pRows } = listData();
  const pColumns = [
    { Header: "文件名", accessor: "fileName", width: "70%", align: "left" },
    { Header: "大小", accessor: "size", align: "left" },
    { Header: "进度", accessor: "schedule", align: "center" },
    { Header: "剩余时间", accessor: "remainder", align: "center" },
    { Header: "下载速度", accessor: "downloadSpeed", align: "center" },
  ];

  const pRows = data.map((item) => {
    let fileName = "";
    if (
      item.bittorrent.info &&
      typeof item.bittorrent.info != "undefined" &&
      item.bittorrent.info != 0
    ) {
      fileName = item.bittorrent.info.name;
    } else if (
      item.files[0].path &&
      typeof item.files[0].path != "undefined" &&
      item.files[0].path != 0
    ) {
      fileName = item.files[0].path;
    }
    fileName = substrLength(fileName, 40);
    let size = byteConversion(item.totalLength);
    let schedule = 0;
    let remainder = "00:00:00";
    if (item.totalLength && item.totalLength != 0) {
      schedule = Math.floor((item.completedLength / item.totalLength) * 100);
    }
    if (item.downloadSpeed && item.downloadSpeed != 0) {
      remainder = formatSeconds(item.totalLength / item.downloadSpeed);
    }
    let downloadSpeed = byteConversion(item.downloadSpeed);
    return {
      fileName: <Project name={fileName} />,
      size: (
        <MDTypography component="a" href="#" variant="button" color="text" fontWeight="medium">
          {size}
        </MDTypography>
      ),
      schedule: <Progress color="info" value={schedule} />,
      remainder: (
        <MDTypography component="a" href="#" variant="caption" color="text" fontWeight="medium">
          {remainder}
        </MDTypography>
      ),
      downloadSpeed: (
        <MDTypography component="a" href="#" variant="caption" color="text" fontWeight="medium">
          {downloadSpeed}/s
        </MDTypography>
      ),
    };
  });

  return (
    <DashboardLayout>
      <DashboardNavbar />
      <MDBox pt={0} pb={2}>
        <Grid container spacing={6}>
          <Grid item xs={12}>
            <Card>
              {/* <MDBox
                mx={2}
                mt={-3}
                py={3}
                px={2}
                variant="gradient"
                bgColor="info"
                borderRadius="lg"
                coloredShadow="info"
              >
                <MDTypography variant="h6" color="white">
                  正在下载
                </MDTypography>
              </MDBox> */}
              <MDBox pt={0.5}>
                <DownloadList
                  table={{ columns: pColumns, rows: pRows }}
                  isSorted={false}
                  entriesPerPage={false}
                  showTotalEntries={false}
                  noEndBorder
                />
              </MDBox>
            </Card>
          </Grid>
        </Grid>
      </MDBox>
      <Footer />
    </DashboardLayout>
  );
}

export default Downloading;
